package net.projects.pro2_atm;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.net.Socket;
import java.util.Scanner;

public class AtmClient {
    private static final Logger log=Logger.getLogger(AtmClient.class.getName());
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost",12000);
            Scanner keyBoard=new Scanner(System.in);
            //获取输出流
            PrintWriter pw=new PrintWriter(socket.getOutputStream());
            //获取服务器的响应
            Scanner sc = new Scanner(socket.getInputStream());
            log.info("链接ATM服务器"+socket.getRemoteSocketAddress()+"成功");
            while (true){
                System.out.println("========银行ATM==============");
                System.out.println("1. 存钱");
                System.out.println("2. 取钱");
                System.out.println("3. 查询");
                System.out.println("4. 退出");
                System.out.println("5. 错误");
                System.out.println("==========================");
                System.out.println("输入您的操作");
                String command = keyBoard.nextLine();
                String response=null;
                if ("1".equalsIgnoreCase(command)){
                    pw.println("DEPOSIT 1 100");
                }else if ("2".equalsIgnoreCase(command)){
                    pw.println("WITHDRAW 1 10");
                }else if ("3".equalsIgnoreCase(command)){
                    pw.println("BALANCE 1");
                }else if ("4".equalsIgnoreCase(command)){
                    pw.println("QUIT");
                    pw.flush();
                    break;
                }else if ("5".equalsIgnoreCase(command)){
                    pw.println("ERROR");
                }else {
                    pw.println("QUIT");
                    pw.flush();
                    break;
                }
                pw.flush();
                response=sc.nextLine();
                System.out.println("服务器响应"+response);
                Gson gson = new Gson();
                Type type=new TypeToken< Jsonmodel<BankAccount> >(){}.getType();
                Jsonmodel<BankAccount> jm = gson.fromJson(response, type);
                if (jm.getCode()==1){
                    BankAccount obj = jm.getObj();
                    System.out.println(obj.getId()+obj.getBalance());
                }else {
                    log.error("错误");
                }
            }
            System.out.println("ATM退出成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
